# 安装依赖：pip install pandas openpyxl tkinter tkcalendar
import tkinter as tk
from tkinter import messagebox, ttk, font
from tkcalendar import DateEntry  # 日期选择组件
import pandas as pd
from datetime import datetime
import json
import os

# ------------------- 界面美化配置 -------------------
class UITheme:
    """界面主题配置类"""
    # 主色调
    PRIMARY_COLOR = "#2E86AB"      # 深蓝色
    SECONDARY_COLOR = "#A23B72"    # 紫红色
    ACCENT_COLOR = "#F18F01"       # 橙色
    SUCCESS_COLOR = "#C73E1D"      # 绿色
    
    # 背景色
    BG_LIGHT = "#F8F9FA"          # 浅灰白
    BG_MEDIUM = "#E9ECEF"         # 中灰
    BG_DARK = "#343A40"           # 深灰
    
    # 文字色
    TEXT_DARK = "#212529"         # 深色文字
    TEXT_MEDIUM = "#6C757D"       # 中等文字
    TEXT_LIGHT = "#FFFFFF"        # 浅色文字
    
    # 边框色
    BORDER_COLOR = "#DEE2E6"      # 边框色
    
    # 渐变色
    GRADIENT_START = "#667eea"    # 渐变开始
    GRADIENT_END = "#764ba2"      # 渐变结束

def configure_styles():
    """配置TTK样式"""
    style = ttk.Style()
    
    # 配置主题
    style.theme_use('clam')
    
    # 配置标签框样式
    style.configure("Custom.TLabelframe", 
                   background=UITheme.BG_LIGHT,
                   borderwidth=2,
                   relief="ridge")
    style.configure("Custom.TLabelframe.Label", 
                   background=UITheme.BG_LIGHT,
                   foreground=UITheme.PRIMARY_COLOR,
                   font=("Microsoft YaHei", 11, "bold"))
    
    # 配置按钮样式
    style.configure("Primary.TButton",
                   background=UITheme.PRIMARY_COLOR,
                   foreground=UITheme.TEXT_LIGHT,
                   borderwidth=0,
                   font=("Microsoft YaHei", 9, "bold"),
                   padding=(15, 8))
    style.map("Primary.TButton",
              background=[('active', UITheme.SECONDARY_COLOR),
                         ('pressed', UITheme.ACCENT_COLOR)])
    
    style.configure("Success.TButton",
                   background=UITheme.SUCCESS_COLOR,
                   foreground=UITheme.TEXT_LIGHT,
                   borderwidth=0,
                   font=("Microsoft YaHei", 9, "bold"),
                   padding=(15, 8))
    style.map("Success.TButton",
              background=[('active', "#28a745"),
                         ('pressed', "#1e7e34")])
    
    style.configure("Warning.TButton",
                   background=UITheme.ACCENT_COLOR,
                   foreground=UITheme.TEXT_LIGHT,
                   borderwidth=0,
                   font=("Microsoft YaHei", 9, "bold"),
                   padding=(15, 8))
    style.map("Warning.TButton",
              background=[('active', "#e67e00"),
                         ('pressed', "#cc6600")])
    
    # 配置输入框样式
    style.configure("Custom.TEntry",
                   borderwidth=1,
                   relief="solid",
                   fieldbackground=UITheme.TEXT_LIGHT,
                   padding=(8, 6))
    
    # 配置表格样式
    style.configure("Custom.Treeview",
                   background=UITheme.TEXT_LIGHT,
                   foreground=UITheme.TEXT_DARK,
                   rowheight=30,
                   borderwidth=1,
                   relief="solid")
    style.configure("Custom.Treeview.Heading",
                   background=UITheme.PRIMARY_COLOR,
                   foreground=UITheme.TEXT_LIGHT,
                   font=("Microsoft YaHei", 10, "bold"),
                   borderwidth=1,
                   relief="solid")
    style.map("Custom.Treeview",
              background=[('selected', UITheme.SECONDARY_COLOR)])
    
    # 配置标签样式
    style.configure("Title.TLabel",
                   background=UITheme.BG_LIGHT,
                   foreground=UITheme.PRIMARY_COLOR,
                   font=("Microsoft YaHei", 10, "bold"))
    
    style.configure("Stats.TLabel",
                   background=UITheme.BG_LIGHT,
                   foreground=UITheme.TEXT_DARK,
                   font=("Microsoft YaHei", 12, "bold"))

# ------------------- 全局变量 -------------------
data_list = []  # 存储录入的订单数据（不设置默认数据，所有数据都为录入数据）
DATA_FILE = "order_data.json"  # 数据文件路径
# Excel列顺序（与原始表格对齐）
COLUMNS = ["序号", "日期", "客户名称", "订单号", "订单金额", "已付金额", "未付金额"]


# ------------------- 数据存储函数 -------------------
def save_data():
    """保存数据到本地文件"""
    try:
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(data_list, f, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"保存数据失败：{str(e)}")


def load_data():
    """从本地文件加载数据"""
    global data_list
    try:
        if os.path.exists(DATA_FILE):
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                data_list = json.load(f)
            print(f"成功加载 {len(data_list)} 条记录")
        else:
            print("数据文件不存在，使用空数据")
            data_list = []
    except Exception as e:
        print(f"加载数据失败：{str(e)}")
        data_list = []


# ------------------- 界面函数 -------------------
def refresh_table():
    """刷新数据表格显示"""
    # 清空表格
    for item in tree.get_children():
        tree.delete(item)
    
    # 插入数据
    for i, data in enumerate(data_list):
        unpaid = data["订单金额"] - data["已付金额"]
        
        # 插入行
        item = tree.insert("", "end", values=(
            i + 1,  # 序号
            data["日期"],
            data["客户名称"],
            data["订单号"],
            f"¥ {data['订单金额']:,.0f}",
            f"¥ {data['已付金额']:,.0f}",
            f"¥ {unpaid:,.0f}"
        ))
        
        # 交替行颜色
        if i % 2 == 0:
            tree.set(item, "", "")  # 偶数行保持默认色
        else:
            tree.tag_configure("oddrow", background="#F8F9FA")
            tree.item(item, tags=("oddrow",))
        
        # 如果未付金额大于0，用红色标记
        if unpaid > 0:
            tree.tag_configure("unpaid", foreground=UITheme.ACCENT_COLOR, font=("Microsoft YaHei", 10, "bold"))
            tree.item(item, tags=("unpaid",))
    
    # 更新统计信息
    update_statistics()
    
    # 更新状态栏
    count = len(data_list)
    status_label.config(text=f"共 {count} 条记录 | 数据已自动保存到本地 | 最后更新: {datetime.now().strftime('%H:%M:%S')}")


def update_statistics():
    """更新右侧统计信息"""
    if not data_list:
        total_order_label.config(text="订单总额：¥ 0")
        total_paid_label.config(text="已付总额：¥ 0")
        total_unpaid_label.config(text="未付总额：¥ 0")
        
        # 清空客户统计
        customer_listbox.delete(0, tk.END)
        return
    
    # 计算总计
    total_order = sum(data["订单金额"] for data in data_list)
    total_paid = sum(data["已付金额"] for data in data_list)
    total_unpaid = total_order - total_paid
    
    # 更新总计标签（新的卡片样式）
    total_order_label.config(text=f"订单总额：¥ {total_order:,.0f}")
    total_paid_label.config(text=f"已付总额：¥ {total_paid:,.0f}")
    total_unpaid_label.config(text=f"未付总额：¥ {total_unpaid:,.0f}")
    
    # 客户统计
    customer_stats = {}
    for data in data_list:
        customer = data["客户名称"]
        if customer not in customer_stats:
            customer_stats[customer] = {"订单": 0, "已付": 0, "未付": 0}
        
        customer_stats[customer]["订单"] += data["订单金额"]
        customer_stats[customer]["已付"] += data["已付金额"]
        customer_stats[customer]["未付"] += data["订单金额"] - data["已付金额"]
    
    # 更新客户统计列表
    customer_listbox.delete(0, tk.END)
    customer_listbox.insert(tk.END, "客户查询")
    customer_listbox.insert(tk.END, "")
    for customer, stats in customer_stats.items():
        customer_listbox.insert(tk.END, f"客户：{customer}")
        customer_listbox.insert(tk.END, f"  订单总额：¥ {stats['订单']:,.0f}")
        customer_listbox.insert(tk.END, f"  已付总额：¥ {stats['已付']:,.0f}")
        customer_listbox.insert(tk.END, f"  未付总额：¥ {stats['未付']:,.0f}")
        customer_listbox.insert(tk.END, "")


def clear_inputs():
    """清空输入框"""
    customer_entry.delete(0, tk.END)
    order_no_entry.delete(0, tk.END)
    order_amt_entry.delete(0, tk.END)
    paid_amt_entry.delete(0, tk.END)
    date_entry.set_date(datetime.now())


def validate_number_input(value, action):
    """验证数字输入"""
    if action == '1':  # 插入操作
        try:
            if value:
                float(value)
            return True
        except ValueError:
            return False
    return True


def submit_data():
    """提交订单数据"""
    try:
        # 获取输入值
        date = date_entry.get()  # 格式：yyyy/mm/dd
        customer = customer_entry.get().strip()
        order_no = order_no_entry.get().strip()
        order_amt_str = order_amt_entry.get().strip()
        paid_amt_str = paid_amt_entry.get().strip()
        
        # 验证非空
        if not (date and customer and order_no and order_amt_str and paid_amt_str):
            messagebox.showerror("错误", "请填写完整信息！")
            return
        
        # 转换金额
        order_amt = float(order_amt_str)
        paid_amt = float(paid_amt_str)
        
        # 验证金额有效性
        if order_amt <= 0 or paid_amt < 0:
            messagebox.showerror("错误", "金额必须为正数，已付金额不能为负数！")
            return
        
        if paid_amt > order_amt:
            messagebox.showerror("错误", "已付金额不能超过订单金额！")
            return
        
        # 封装数据
        data_list.append({
            "日期": date,
            "客户名称": customer,
            "订单号": order_no,
            "订单金额": order_amt,
            "已付金额": paid_amt
        })
        
        # 保存数据到文件
        save_data()
        
        # 清空输入框
        date_entry.set_date(datetime.now())  # 重置为当前日期
        customer_entry.delete(0, tk.END)
        order_no_entry.delete(0, tk.END)
        order_amt_entry.delete(0, tk.END)
        paid_amt_entry.delete(0, tk.END)
        
        # 刷新表格显示
        refresh_table()
        
        messagebox.showinfo("成功", "数据提交成功！")
        
    except ValueError:
        messagebox.showerror("错误", "金额需输入数字！")
    except Exception as e:
        messagebox.showerror("错误", f"提交失败：{str(e)}")


def delete_selected():
    """删除选中的记录"""
    selection = tree.selection()
    if not selection:
        messagebox.showwarning("警告", "请选择要删除的记录！")
        return
    
    if messagebox.askyesno("确认", "确定要删除选中的记录吗？"):
        # 获取选中项的索引
        item = selection[0]
        index = tree.index(item)
        
        # 删除数据
        del data_list[index]
        
        # 保存数据到文件
        save_data()
        
        # 刷新表格
        refresh_table()
        
        messagebox.showinfo("成功", "记录删除成功！")


def edit_selected():
    """编辑选中的记录"""
    selection = tree.selection()
    if not selection:
        messagebox.showwarning("警告", "请选择要编辑的记录！")
        return
    
    try:
        # 获取输入值
        date = date_entry.get()
        customer = customer_entry.get().strip()
        order_no = order_no_entry.get().strip()
        order_amt_str = order_amt_entry.get().strip()
        paid_amt_str = paid_amt_entry.get().strip()
        
        # 验证非空
        if not (date and customer and order_no and order_amt_str and paid_amt_str):
            messagebox.showerror("错误", "请填写完整信息！")
            return
        
        # 转换金额
        order_amt = float(order_amt_str)
        paid_amt = float(paid_amt_str)
        
        # 验证金额有效性
        if order_amt <= 0 or paid_amt < 0:
            messagebox.showerror("错误", "金额必须为正数，已付金额不能为负数！")
            return
        
        if paid_amt > order_amt:
            messagebox.showerror("错误", "已付金额不能超过订单金额！")
            return
        
        # 获取选中项的索引并更新数据
        item = selection[0]
        index = tree.index(item)
        
        data_list[index] = {
            "日期": date,
            "客户名称": customer,
            "订单号": order_no,
            "订单金额": order_amt,
            "已付金额": paid_amt
        }
        
        # 保存数据到文件
        save_data()
        
        # 刷新表格
        refresh_table()
        
        # 清空输入框
        date_entry.set_date(datetime.now())
        customer_entry.delete(0, tk.END)
        order_no_entry.delete(0, tk.END)
        order_amt_entry.delete(0, tk.END)
        paid_amt_entry.delete(0, tk.END)
        
        messagebox.showinfo("成功", "记录编辑成功！")
        
    except ValueError:
        messagebox.showerror("错误", "金额需输入数字！")
    except Exception as e:
        messagebox.showerror("错误", f"编辑失败：{str(e)}")


def on_tree_select(event):
    """表格选择事件"""
    selection = tree.selection()
    if selection:
        item = selection[0]
        index = tree.index(item)
        
        if index < len(data_list):
            data = data_list[index]
            
            # 在输入框中显示选中的数据（用于编辑）
            try:
                date_entry.set_date(datetime.strptime(data["日期"], "%Y/%m/%d"))
            except:
                date_entry.set_date(datetime.now())
            
            customer_entry.delete(0, tk.END)
            customer_entry.insert(0, data["客户名称"])
            order_no_entry.delete(0, tk.END)
            order_no_entry.insert(0, data["订单号"])
            order_amt_entry.delete(0, tk.END)
            order_amt_entry.insert(0, str(data["订单金额"]))
            paid_amt_entry.delete(0, tk.END)
            paid_amt_entry.insert(0, str(data["已付金额"]))


def export_excel():
    """导出数据到Excel（含汇总、客户统计和公式联动）"""
    if not data_list:
        messagebox.showerror("错误", "暂无数据可导出！")
        return
    
    try:
        from openpyxl import Workbook
        from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
        from openpyxl.utils import get_column_letter
        
        # 创建工作簿
        wb = Workbook()
        ws = wb.active
        ws.title = "应收账款统计表"
        
        # 设置样式
        header_font = Font(bold=True, color="FFFFFF")
        header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
        border = Border(
            left=Side(border_style="thin"),
            right=Side(border_style="thin"),
            top=Side(border_style="thin"),
            bottom=Side(border_style="thin")
        )
        
        # 1. 写入表头（第1行）
        headers = ["序号", "日期", "客户名称", "订单号", "订单金额", "已付金额", "未付金额"]
        for col, header in enumerate(headers, 1):
            cell = ws.cell(row=1, column=col)
            cell.value = header
            cell.font = header_font
            cell.fill = header_fill
            cell.border = border
            cell.alignment = Alignment(horizontal="center")
        
        # 2. 写入数据（从第2行开始）
        for row, data in enumerate(data_list, 2):
            ws.cell(row=row, column=1, value=row-1)  # 序号
            ws.cell(row=row, column=2, value=data["日期"])  # 日期
            ws.cell(row=row, column=3, value=data["客户名称"])  # 客户名称
            ws.cell(row=row, column=4, value=data["订单号"])  # 订单号
            ws.cell(row=row, column=5, value=data["订单金额"])  # 订单金额
            ws.cell(row=row, column=6, value=data["已付金额"])  # 已付金额
            
            # 未付金额使用公式计算（实现数据联动）
            ws.cell(row=row, column=7, value=f"=E{row}-F{row}")
            
            # 设置边框
            for col in range(1, 8):
                ws.cell(row=row, column=col).border = border
        
        # 3. 写入汇总统计（I列开始）
        summary_start_row = 2
        ws.cell(row=summary_start_row, column=9, value="汇总统计").font = Font(bold=True)
        ws.cell(row=summary_start_row+1, column=9, value="订单总额")
        ws.cell(row=summary_start_row+1, column=10, value=f"=SUM(E2:E{len(data_list)+1})")  # 公式求和
        ws.cell(row=summary_start_row+2, column=9, value="已付总额")
        ws.cell(row=summary_start_row+2, column=10, value=f"=SUM(F2:F{len(data_list)+1})")  # 公式求和
        ws.cell(row=summary_start_row+3, column=9, value="未付总额")
        ws.cell(row=summary_start_row+3, column=10, value=f"=SUM(G2:G{len(data_list)+1})")  # 公式求和
        
        # 4. 写入客户统计（L列开始）
        customer_start_row = 2
        ws.cell(row=customer_start_row, column=12, value="客户查询").font = Font(bold=True)
        
        # 客户分组统计
        customer_stats = {}
        for data in data_list:
            customer = data["客户名称"]
            if customer not in customer_stats:
                customer_stats[customer] = {"rows": []}
            customer_stats[customer]["rows"].append(data)
        
        current_row = customer_start_row + 1
        for customer, stats in customer_stats.items():
            ws.cell(row=current_row, column=12, value=f"客户：{customer}").font = Font(bold=True)
            current_row += 1
            
            # 计算该客户的行范围
            customer_rows = []
            for i, data in enumerate(data_list, 2):
                if data["客户名称"] == customer:
                    customer_rows.append(str(i))
            
            if customer_rows:
                rows_range = ",".join([f"E{r}" for r in customer_rows])
                ws.cell(row=current_row, column=12, value="订单总额")
                ws.cell(row=current_row, column=13, value=f"=SUM({rows_range})")
                current_row += 1
                
                rows_range = ",".join([f"F{r}" for r in customer_rows])
                ws.cell(row=current_row, column=12, value="已付总额")
                ws.cell(row=current_row, column=13, value=f"=SUM({rows_range})")
                current_row += 1
                
                rows_range = ",".join([f"G{r}" for r in customer_rows])
                ws.cell(row=current_row, column=12, value="未付总额")
                ws.cell(row=current_row, column=13, value=f"=SUM({rows_range})")
                current_row += 2  # 空行分隔
        
        # 5. 设置列宽
        column_widths = {
            'A': 8,   # 序号
            'B': 12,  # 日期
            'C': 15,  # 客户名称
            'D': 15,  # 订单号
            'E': 15,  # 订单金额
            'F': 15,  # 已付金额
            'G': 15,  # 未付金额
            'I': 12,  # 汇总标题
            'J': 15,  # 汇总金额
            'L': 12,  # 客户名称
            'M': 15,  # 客户金额
        }
        
        for col, width in column_widths.items():
            ws.column_dimensions[col].width = width
        
        # 6. 设置数值格式
        for row in range(2, len(data_list) + 2):
            # 金额列设置为货币格式
            for col in [5, 6, 7]:  # E, F, G列
                ws.cell(row=row, column=col).number_format = '¥#,##0'
        
        # 汇总统计金额格式
        for row in range(summary_start_row+1, summary_start_row+4):
            ws.cell(row=row, column=10).number_format = '¥#,##0'
        
        # 客户统计金额格式
        for row in range(2, current_row):
            if ws.cell(row=row, column=13).value:
                ws.cell(row=row, column=13).number_format = '¥#,##0'
        
        # 保存文件
        filename = "应收账款统计表.xlsx"
        wb.save(filename)
        
        messagebox.showinfo("成功", f"导出完成！文件：{filename}\n特点：\n• 未付金额自动计算（公式联动）\n• 汇总统计实时更新\n• 客户统计自动分组")
    
    except Exception as e:
        messagebox.showerror("错误", f"导出失败：{str(e)}")


# ------------------- 界面搭建 -------------------
# 配置样式
configure_styles()

root = tk.Tk()
root.title("🏢 应收账款统计表 - 专业版")
root.geometry("1400x800")
root.configure(bg=UITheme.BG_LIGHT)

# 设置图标（如果有的话）
try:
    # root.iconbitmap("icon.ico")  # 如果有图标文件可以取消注释
    pass
except:
    pass

# 创建标题栏
title_frame = tk.Frame(root, bg=UITheme.PRIMARY_COLOR, height=60)
title_frame.pack(fill=tk.X)
title_frame.pack_propagate(False)

title_label = tk.Label(title_frame, 
                      text="📊 应收账款统计管理系统", 
                      bg=UITheme.PRIMARY_COLOR,
                      fg=UITheme.TEXT_LIGHT,
                      font=("Microsoft YaHei", 16, "bold"))
title_label.pack(expand=True)

subtitle_label = tk.Label(title_frame, 
                         text="Professional Accounts Receivable Management System", 
                         bg=UITheme.PRIMARY_COLOR,
                         fg=UITheme.BG_MEDIUM,
                         font=("Arial", 10))
subtitle_label.pack()

# 创建主框架
main_frame = ttk.Frame(root)
main_frame.pack(fill=tk.BOTH, expand=True, padx=15, pady=15)

# 左侧输入区域
input_frame = ttk.LabelFrame(main_frame, text="📝 订单录入", padding=15, style="Custom.TLabelframe")
input_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 8))

# 添加输入验证
vcmd = (root.register(validate_number_input), '%P', '%d')

# 组件：日期
date_label = ttk.Label(input_frame, text="📅 日期：", style="Title.TLabel")
date_entry = DateEntry(
    input_frame, date_pattern="yyyy/mm/dd",  # 匹配表格日期格式
    background=UITheme.TEXT_LIGHT, 
    foreground=UITheme.TEXT_DARK, 
    borderwidth=2, 
    width=18,
    font=("Microsoft YaHei", 10)
)
date_entry.set_date(datetime.now())  # 默认当前日期

# 组件：客户名称
customer_label = ttk.Label(input_frame, text="👤 客户名称：", style="Title.TLabel")
customer_entry = ttk.Entry(input_frame, width=25, font=("Microsoft YaHei", 10), style="Custom.TEntry")

# 组件：订单号
order_no_label = ttk.Label(input_frame, text="📋 订单号：", style="Title.TLabel")
order_no_entry = ttk.Entry(input_frame, width=25, font=("Microsoft YaHei", 10), style="Custom.TEntry")

# 组件：订单金额
order_amt_label = ttk.Label(input_frame, text="💰 订单金额：", style="Title.TLabel")
order_amt_entry = ttk.Entry(input_frame, width=25, font=("Microsoft YaHei", 10), 
                           style="Custom.TEntry", validate='key', validatecommand=vcmd)

# 组件：已付金额
paid_amt_label = ttk.Label(input_frame, text="✅ 已付金额：", style="Title.TLabel")
paid_amt_entry = ttk.Entry(input_frame, width=25, font=("Microsoft YaHei", 10), 
                          style="Custom.TEntry", validate='key', validatecommand=vcmd)

# 按钮框架
button_frame = ttk.Frame(input_frame)

# 按钮：提交、编辑、删除、导出、清空
submit_btn = ttk.Button(button_frame, text="✅ 提交数据", command=submit_data, style="Primary.TButton")
edit_btn = ttk.Button(button_frame, text="✏️ 编辑选中", command=edit_selected, style="Warning.TButton")
delete_btn = ttk.Button(button_frame, text="🗑️ 删除选中", command=delete_selected, style="Warning.TButton")
clear_btn = ttk.Button(button_frame, text="🆕 清空输入", command=clear_inputs, style="Primary.TButton")
export_btn = ttk.Button(button_frame, text="📊 导出Excel", command=export_excel, style="Success.TButton")

# 输入区域布局（改进间距和对齐）
date_label.grid(row=0, column=0, padx=8, pady=8, sticky="w")
date_entry.grid(row=0, column=1, padx=8, pady=8, sticky="ew")
customer_label.grid(row=1, column=0, padx=8, pady=8, sticky="w")
customer_entry.grid(row=1, column=1, padx=8, pady=8, sticky="ew")
order_no_label.grid(row=2, column=0, padx=8, pady=8, sticky="w")
order_no_entry.grid(row=2, column=1, padx=8, pady=8, sticky="ew")
order_amt_label.grid(row=3, column=0, padx=8, pady=8, sticky="w")
order_amt_entry.grid(row=3, column=1, padx=8, pady=8, sticky="ew")
paid_amt_label.grid(row=4, column=0, padx=8, pady=8, sticky="w")
paid_amt_entry.grid(row=4, column=1, padx=8, pady=8, sticky="ew")

# 按钮布局（垂直排列）
button_frame.grid(row=5, column=0, columnspan=2, pady=15, sticky="ew")
submit_btn.pack(pady=3, fill=tk.X)
edit_btn.pack(pady=3, fill=tk.X)
delete_btn.pack(pady=3, fill=tk.X)
clear_btn.pack(pady=3, fill=tk.X)
export_btn.pack(pady=3, fill=tk.X)

# 配置输入区域的列权重
input_frame.grid_columnconfigure(1, weight=1)

# 中间表格区域
table_frame = ttk.LabelFrame(main_frame, text="📈 应收账款统计表", padding=15, style="Custom.TLabelframe")
table_frame.grid(row=0, column=1, sticky="nsew", padx=8)

# 创建Treeview表格
columns = ("序号", "日期", "客户名称", "订单号", "订单金额", "已付金额", "未付金额")
tree = ttk.Treeview(table_frame, columns=columns, show="headings", height=18, style="Custom.Treeview")

# 设置列标题和宽度
tree.heading("序号", text="序号")
tree.heading("日期", text="日期")
tree.heading("客户名称", text="客户名称")
tree.heading("订单号", text="订单号")
tree.heading("订单金额", text="订单金额")
tree.heading("已付金额", text="已付金额")
tree.heading("未付金额", text="未付金额")

tree.column("序号", width=60, anchor=tk.CENTER)
tree.column("日期", width=110, anchor=tk.CENTER)
tree.column("客户名称", width=120, anchor=tk.CENTER)
tree.column("订单号", width=120, anchor=tk.CENTER)
tree.column("订单金额", width=130, anchor=tk.E)
tree.column("已付金额", width=130, anchor=tk.E)
tree.column("未付金额", width=130, anchor=tk.E)

# 绑定选择事件
tree.bind("<<TreeviewSelect>>", on_tree_select)

# 添加滚动条
scrollbar = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=tree.yview)
tree.configure(yscrollcommand=scrollbar.set)

# 表格布局
tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# 右侧统计区域
stats_frame = ttk.LabelFrame(main_frame, text="📊 汇总统计", padding=15, style="Custom.TLabelframe")
stats_frame.grid(row=0, column=2, sticky="nsew", padx=(8, 0))

# 总计标签（使用卡片式布局）
# 订单总额卡片
order_card = tk.Frame(stats_frame, bg=UITheme.PRIMARY_COLOR, relief="raised", bd=2)
order_card.pack(fill=tk.X, pady=5)
total_order_label = tk.Label(order_card, text="订单总额：¥ 0", 
                            bg=UITheme.PRIMARY_COLOR, 
                            fg=UITheme.TEXT_LIGHT,
                            font=("Microsoft YaHei", 12, "bold"),
                            pady=10)
total_order_label.pack()

# 已付总额卡片
paid_card = tk.Frame(stats_frame, bg=UITheme.SUCCESS_COLOR, relief="raised", bd=2)
paid_card.pack(fill=tk.X, pady=5)
total_paid_label = tk.Label(paid_card, text="已付总额：¥ 0", 
                           bg=UITheme.SUCCESS_COLOR, 
                           fg=UITheme.TEXT_LIGHT,
                           font=("Microsoft YaHei", 12, "bold"),
                           pady=10)
total_paid_label.pack()

# 未付总额卡片
unpaid_card = tk.Frame(stats_frame, bg=UITheme.ACCENT_COLOR, relief="raised", bd=2)
unpaid_card.pack(fill=tk.X, pady=5)
total_unpaid_label = tk.Label(unpaid_card, text="未付总额：¥ 0", 
                             bg=UITheme.ACCENT_COLOR, 
                             fg=UITheme.TEXT_LIGHT,
                             font=("Microsoft YaHei", 12, "bold"),
                             pady=10)
total_unpaid_label.pack()

# 客户统计区域
customer_frame = ttk.LabelFrame(stats_frame, text="👥 客户查询", padding=8, style="Custom.TLabelframe")
customer_frame.pack(fill=tk.BOTH, expand=True, pady=(15, 0))

customer_listbox = tk.Listbox(customer_frame, height=15, 
                             font=("Microsoft YaHei", 10),
                             bg=UITheme.TEXT_LIGHT,
                             fg=UITheme.TEXT_DARK,
                             selectbackground=UITheme.SECONDARY_COLOR,
                             selectforeground=UITheme.TEXT_LIGHT,
                             relief="flat",
                             bd=1)
customer_scrollbar = ttk.Scrollbar(customer_frame, orient=tk.VERTICAL, command=customer_listbox.yview)
customer_listbox.configure(yscrollcommand=customer_scrollbar.set)

customer_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
customer_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# 配置网格权重
main_frame.grid_columnconfigure(1, weight=2)  # 表格区域权重更大
main_frame.grid_columnconfigure(0, weight=1)  # 输入区域
main_frame.grid_columnconfigure(2, weight=1)  # 统计区域
main_frame.grid_rowconfigure(0, weight=1)

# 状态栏
status_frame = tk.Frame(root, bg=UITheme.BG_MEDIUM, height=25)
status_frame.pack(fill=tk.X, side=tk.BOTTOM)
status_frame.pack_propagate(False)

status_label = tk.Label(status_frame, 
                       text="就绪 | 数据已自动保存到本地", 
                       bg=UITheme.BG_MEDIUM,
                       fg=UITheme.TEXT_MEDIUM,
                       font=("Microsoft YaHei", 9))
status_label.pack(side=tk.LEFT, padx=10, pady=2)

# 程序启动时加载数据
load_data()

# 初始化表格
refresh_table()

if __name__ == "__main__":
    root.mainloop()
